package com.stellar.circle.basic.dao;

import com.stellar.circle.basic.entity.SChatMessage;
import com.stellar.circle.controller.admin.sChatMessage.vo.SChatMessageResponseVO;
import org.apache.ibatis.annotations.*;

import java.util.List;

/**
 * 私聊消息表(SChatMessage)数据访问层
 *
 * @author Jqchan
 * @since 2025-06-12 21:21:20
 */
public interface SChatMessageDao {

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键ID
     */
    SChatMessage queryById(@Param("id") Long id);

    /**
     * 条件查询单条结果
     *
     * @param condition 查询条件
     */
    SChatMessage queryByCondition(@Param("condition") SChatMessage condition);

    /**
     * 条件查询所有结果
     *
     * @param condition 查询条件
     */
    List<SChatMessage> queryAllByCondition(@Param("condition") SChatMessage condition);

    /**
     * 分页查询
     *
     * @param condition 查询条件
     * @param page      页码
     * @param pageSize  每页数量
     */
    List<SChatMessage> page(@Param("condition") SChatMessage condition,
                            @Param("page") int page,
                            @Param("pageSize") int pageSize);

    /**
     * 条件统计
     *
     * @param condition 统计条件
     */
    Long count(@Param("condition") SChatMessage condition);

    /**
     * 新增数据
     *
     * @param entity 实例对象
     */
    int insert(@Param("entity") SChatMessage entity);

    /**
     * 批量新增
     *
     * @param entities 实例列表
     */
    int insertBatch(@Param("entities") List<SChatMessage> entities);

    /**
     * 更新数据
     *
     * @param entity 实例对象
     */
    int update(@Param("entity") SChatMessage entity);

    /**
     * 通过主键删除
     *
     * @param id 主键ID
     */
    int deleteById(@Param("id") Long id);

    /**
     * 批量更新 - 标记为已读
     *
     * @param messageId
     */
    @Update("UPDATE s_chat_message SET is_read = 1 WHERE id IN (#{messageIds})")
    void markAsRead(@Param("messageId") List<Long> messageId);


    /**
     * 查询未读消息
     *
     * @param userId
     * @return
     */
    @Select("SELECT * FROM s_chat_message " +
            "WHERE receiver_id = #{userId} AND is_read = 0 AND is_deleted = 0")
    List<SChatMessage> selectUnreadByUserId(@Param("userId") Long userId);


    /**
     * 查询历史消息
     *
     * @param conversationId
     * @param lastMsgId
     * @param limit
     * @return
     */
    @Select("SELECT * FROM s_chat_message " +
            "WHERE conversation_id = #{conversationId} AND id < #{lastMsgId} " +
            "AND is_deleted = 0 ORDER BY id DESC LIMIT #{limit}")
    List<SChatMessage> selectHistory(@Param("conversationId") String conversationId,
                                     @Param("lastMsgId") Long lastMsgId,
                                     @Param("limit") int limit);


    /**
     * 获取当前用户的聊天会话列表（分页），支持陌生人聊天
     *
     * @param userId
     * @param page
     * @param pageSize
     * @return
     */
    @Select("SELECT " +
            "   other_user.id AS friend_id, " +
            "   other_user.avatar, " +
            "   other_user.nick_name, " +
            "   COALESCE(unread.unread_count, 0) AS unread_count, " +
            "   last_msg.content AS last_message, " +
            "   last_msg.create_time AS last_message_time, " +
            "   CASE WHEN rel.id IS NOT NULL THEN 1 ELSE 0 END AS is_friend " +
            "FROM ( " +
            "   SELECT DISTINCT " +
            "       CASE " +
            "           WHEN sender_id = #{userId} THEN receiver_id " +
            "           ELSE sender_id " +
            "       END AS other_user_id " +
            "   FROM s_chat_message " +
            "   WHERE (sender_id = #{userId} OR receiver_id = #{userId}) " +
            "     AND is_deleted = 0 " +
            ") distinct_users " +
            "JOIN auth_user other_user ON other_user.id = distinct_users.other_user_id " +
            "LEFT JOIN s_chat_relationship rel " +
            "   ON rel.user_id = #{userId} " +
            "   AND rel.friend_id = other_user.id " +
            "   AND rel.is_deleted = 0 " +
            "LEFT JOIN ( " +
            "   SELECT receiver_id, sender_id, COUNT(*) AS unread_count " +
            "   FROM s_chat_message " +
            "   WHERE receiver_id = #{userId} " +
            "     AND is_read = 0 " +
            "   AND is_hidden = 0 " +
            "     AND is_deleted = 0 " +
            "   GROUP BY sender_id " +
            ") unread ON unread.sender_id = other_user.id " +
            "LEFT JOIN ( " +
            "   SELECT m1.* " +
            "   FROM s_chat_message m1 " +
            "   INNER JOIN ( " +
            "       SELECT " +
            "           conversation_id, " +
            "           MAX(create_time) AS max_time " +
            "       FROM s_chat_message " +
            "       WHERE (sender_id = #{userId} OR receiver_id = #{userId}) " +
            "         AND is_deleted = 0 " +
            "       GROUP BY conversation_id " +
            "   ) m2 ON m1.conversation_id = m2.conversation_id AND m1.create_time = m2.max_time " +
            ") last_msg ON last_msg.conversation_id = CONCAT(LEAST(#{userId}, other_user.id), '_', GREATEST(#{userId}, other_user.id)) " +
            "ORDER BY COALESCE(last_msg.create_time, '1970-01-01') DESC " +
            "LIMIT #{offset}, #{pageSize}")
    @Results({
            @Result(property = "friendId", column = "friend_id"),
            @Result(property = "avatar", column = "avatar"),
            @Result(property = "nickname", column = "nick_name"),
            @Result(property = "unreadCount", column = "unread_count"),
            @Result(property = "lastMessage", column = "last_message"),
            @Result(property = "lastMessageTime", column = "last_message_time"),
            @Result(property = "isFriend", column = "is_friend")
    })
    List<SChatMessageResponseVO> getMessageList(Long userId, int page, int pageSize);

    @Select("SELECT COUNT(DISTINCT other_user_id) " +
            "FROM ( " +
            "   SELECT " +
            "       CASE " +
            "           WHEN sender_id = #{userId} THEN receiver_id " +
            "           ELSE sender_id " +
            "       END AS other_user_id " +
            "   FROM s_chat_message " +
            "   WHERE (sender_id = #{userId} OR receiver_id = #{userId}) " +
            "     AND is_deleted = 0 " +
            ") distinct_users")
    Long countChatList(Long userId);
}

